package com.boxin.ims.modules.wechat.busi;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.momarketing.entity.Coupon;
import com.boxin.ims.modules.momarketing.entity.CouponConfig;
import com.boxin.ims.modules.momarketing.service.CouponConfigService;
import com.boxin.ims.modules.momarketing.service.CouponService;
import com.boxin.ims.modules.wechat.entity.NewsReply;
import com.boxin.ims.modules.wechat.entity.SeckillGainer;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.thinkgem.jeesite.common.utils.StringUtils;

@Service
public class CouponProcessor extends BusinessProcessor{
	
	public static final String  BIRTHDAY_COUPON ="生日优惠券";
	
	@Autowired
	private CouponConfigService couponConfigService;
	
	@Autowired
	private CouponService couponService;
	
	@Autowired
	private WechatDaoHelper wechatDaoHelper;
	
	public CouponProcessor(){
		super();
	}
	

	@Override
	public ProcessMessage process() {
		
		WechatMember member = memberCheckAndReply();
		if(member!=null){
			
			String keywords = this.textMessage.getContent();
			//生日优惠券
			CouponConfig config = couponConfigService.getByUserIdAndKeywords(user.getId(),keywords);	//优惠券配置
			if(BIRTHDAY_COUPON.equals(keywords)){
				processBirthdayCoupon(member);
				return null;
			}
			
			
			if(config == null){//未找到对应的优惠券
				String reply = "亲,对不起，您输入的格式不正确无法找到对应的优惠券,请查证后再重新输入获取,谢谢!";
				writeToUser(reply);
				return null;
				
			} 
			
			
			if(!config.getRepeats()){	//不允许重复的话
				Map<String,String> params = new HashMap<String,String>();
//				params.put("day", DateUtils.getTodayString());
//				params.put("memberId", member.getId()+"");
//				params.put("keywords", textMessage.getContent());
//				params.put("openId", member.getWechatId());
				params.put("userId", member.getUser().getId()+"");
				params.put("memberId", member.getId()+"");
				params.put("configId", config.getId()+"");
				int cnt = wechatDaoHelper.getMyTodayCouponCount(params);
				if(cnt>0){
					String reply = "亲,对不起，您已经获取过当天的【"+config.getName()+"】了,无法再重复获取,每人每天只能获取一份同一种类的优惠券,谢谢!";
					//writeToUser(reply);
					List<Map<String,Object>>  myCoupons = wechatDaoHelper.queryCoupons(params);
					Map<String,Object> couponMap = myCoupons.get(0);
					Long qrcodeId = Long.parseLong(couponMap.get("qrcode_id").toString());
					String title = "您有未使用的微会员特价【" + couponMap.get("name")	+ "】";
//					if(config!=null && StringUtils.isNotEmpty(config.getQrcodeTitle())){
//						title = config.getQrcodeTitle();
//					}
					Date endTime = (Date)couponMap.get("end_time");
							
					String validDate = DateUtils.formatDate((endTime==null)?new Date():endTime, "MM月dd日");
					String desc = "您有未使用的【"+config.getName()+"】,请于"+validDate+"之前到店里使用后再重新获取吧,过期作废，谢谢！";
//					if(config != null && StringUtils.isNotEmpty(config.getQrcodeDesc())){
//						desc = config.getQrcodeDesc();
//					}
					writeImageToUser(title, desc, qrcodeId);
					return null;
					
				}
			}else{	//允许重但超多最多次数
				Map<String,String> params = new HashMap<String,String>();
//				params.put("day", DateUtils.getTodayString());
//				params.put("openId", member.getWechatId());
				params.put("userId", member.getUser().getId()+"");
				params.put("memberId", member.getId()+"");
				params.put("configId", config.getId()+"");
				int cnt = wechatDaoHelper.getMyTodayCouponCount(params);
				if(config.getRepeatCount() != null && config.getRepeatCount() != 0){	//0代表无限次数
					
					if(cnt>=config.getRepeatCount()){
						String reply = "亲,对不起，您有"+cnt+"个微会员特价优惠券还未使用,无法再重复获取，请将已获得的优惠使用后再重新获取,谢谢!";
						//writeToUser(reply);
						//此处应该将已生的发给用户
						List<Map<String,Object>>  myCoupons = wechatDaoHelper.queryCoupons(params);
						if(cnt==1){
							Map<String,Object> couponMap = myCoupons.get(0);
							Long qrcodeId = Long.parseLong(couponMap.get("qrcode_id").toString());
							String title = "您有未使用的微会员特价【" + couponMap.get("name")	+ "】";
//							if(config!=null && StringUtils.isNotEmpty(config.getQrcodeTitle())){
//								title = config.getQrcodeTitle();
//							}
							Date endTime = (Date)couponMap.get("end_time");
									
							String validDate = DateUtils.formatDate((endTime==null)?new Date():endTime, "MM月dd日");
							String desc = "您有未使用的【"+config.getName()+"】,请于"+validDate+"之前到店里使用后再重新获取吧,过期作废，谢谢！";
//							if(config != null && StringUtils.isNotEmpty(config.getQrcodeDesc())){
//								desc = config.getQrcodeDesc();
//							}
							writeImageToUser(title, desc, qrcodeId);
							return null;
							
						}else{
							
							List<NewsReply> newsReplies = new ArrayList<NewsReply>();
							for(Map<String,Object> map : myCoupons){
								String title = "您有未使用的微会员特价【" + map.get("name")	+ "】";
								Date date = (Date)map.get("end_time");
								String validDate = DateUtils.formatDate((date == null) ? new Date() : date, "MM月dd日");
								String desc = "亲，您有未使用的微会员特价【" +map.get("name") + "】,请于"+ validDate + "之前到店里凭此二维码核销使用，过期作废，谢谢！";
								Long qrcodeId = Long.parseLong(map.get("qrcode_id").toString());
								NewsReply newsReply = new NewsReply();
								newsReply.setTitle(title);
								newsReply.setDescription(desc);
								newsReply.setPicUrl(QRCodeUtils.getQRCodePNGURL(qrcodeId));
								newsReply.setUrl(QRCodeUtils.getQRCodePNGURL(qrcodeId));
								
								newsReplies.add(newsReply);
							}
							
							writeQueryLotteryImageToUser(newsReplies);
							return null;
							
							
						}
					}
				}
				
				
			}
			
			//有未使用的优惠
			
			//生成优惠券
			Coupon coupon = new Coupon();
			coupon.setUser(weChat.getUser());
			coupon.setSourceId(openId);
			coupon.setConfig(config);
			coupon.setMember(member);
			coupon.setMobile(member.getMobile());
			coupon.setName(config.getName());
			coupon.setStartTime(config.getStartTime());
			coupon.setEndTime(DateUtils.getDelayDate(config.getValidDays()));
			
			couponService.save(coupon);
			
			String title = "微会员特权优惠券";
			if(config!=null && StringUtils.isNotEmpty(config.getQrcodeTitle())){
				title = config.getQrcodeTitle();
			}
			//String validDay  = DateUtils.getDelayDate(config.getValidDays());
			String validDate = DateUtils.formatDate((coupon.getEndTime()==null)?new Date():coupon.getEndTime(), "MM月dd日");
			String desc = "恭喜您成功获得微会员特价【"+config.getName()+"】，请不要删除此信息，于"+validDate+"之前到店里使用，过期作废，谢谢！";
			if(config != null && StringUtils.isNotEmpty(config.getQrcodeDesc())){
				desc = config.getQrcodeDesc();
			}
			
			writeImageToUser(title, desc, coupon.getQrCode().getId());
			
		}
		
		
		return null;
	}

	/**
	 * @author Jakemanse
	 * @time 2013-11-5  下午10:59:08
	 * @function <p> 特殊处理生日优惠券 </p>
	 */
	public void processBirthdayCoupon(WechatMember member){
		String today = DateUtils.getTodayString();
		String reply ="";
		
		if(StringUtils.isEmpty(member.getBirthday())){	//没有填写生日资料
			reply = "亲,您还没有设置您的生日日期,请回复【我的生日+生日日期】如:我的生日19880808,不要添加额外信息，否则系统无法识别您的生日日期，谢谢!";
			writeToUser(reply);
			return ;
			
		}else{
			//是生日
			if(today.substring(4).equals(member.getBirthday().substring(4))){
				
				CouponConfig config = couponConfigService.getByUserIdAndKeywords(user.getId(),BIRTHDAY_COUPON);	//优惠券配置
				if(config == null){	//如果没有生日优惠券配置，则自动新建
					config = new CouponConfig();
					config.setUser(user);
					config.setKeywords(BIRTHDAY_COUPON);
					config.setName(BIRTHDAY_COUPON);
					config.setRepeatCount(1);
					config.setRepeats(false);
					config.setEndTime(new Date());
					config.setValidDays(1);
					
					couponConfigService.save(config);	//保存
				}
				
				Coupon query = new Coupon();
				query.setMember(member);
				query.setConfig(config);
				Date createTime = new Date();
				createTime.setHours(0);
				query.setCreateTime(createTime);
				
				List<Coupon> couponList = 	couponService.find( query);
				
				if(couponList!=null && !couponList.isEmpty()){	//已生成发送
					Coupon coupon = couponList.get(0);
					if(Coupon.STATUS_CLEAR.equals(coupon.getStatus())){	//已核销使用
						reply = "";
						writeToUser(reply);
						return ;
					}else{
						String title = "亲,祝你生日快乐";
						if(config!=null && StringUtils.isNotEmpty(config.getQrcodeTitle())){
							title = config.getQrcodeTitle();
						}
						//String validDay  = DateUtils.getDelayDate(config.getValidDays());
						String desc = "亲,今天是你的生日,祝你生日快乐!!我们特为您准备了【微会员生日特价优惠券】，请不要删除此信息并于当日到店里凭此二维码和您的身份证核实使用，过期作废，谢谢！";
						if(config != null && StringUtils.isNotEmpty(config.getQrcodeDesc())){
							desc = config.getQrcodeDesc();
						}
						
						writeImageToUser(title, desc, coupon.getQrCode().getId());
					}
					
					
				}else{
					
					//生成优惠券
					Coupon coupon = new Coupon();
					coupon.setUser(weChat.getUser());
					coupon.setSourceId(openId);
					coupon.setConfig(config);
					coupon.setMember(member);
					coupon.setMobile(member.getMobile());
					coupon.setName(config.getName());
					Date endTime = new Date();
					endTime.setHours(23);
					endTime.setMinutes(59);
					endTime.setSeconds(59);
					coupon.setEndTime(endTime);
					
					couponService.save(coupon);
					
					String title = "亲,祝你生日快乐";
					if(config!=null && StringUtils.isNotEmpty(config.getQrcodeTitle())){
						title = config.getQrcodeTitle();
					}
					//String validDay  = DateUtils.getDelayDate(config.getValidDays());
					String desc = "亲,今天是你的生日,祝你生日快乐!!我们特为您准备了【微会员生日特价优惠券】，请不要删除此信息并于当日到店里凭此二维码和您的身份证核实使用，过期作废，谢谢！";
					if(config != null && StringUtils.isNotEmpty(config.getQrcodeDesc())){
						desc = config.getQrcodeDesc();
					}
					
					writeImageToUser(title, desc, coupon.getQrCode().getId());
					
				}
				
				return ;
			}else{
				
				reply ="亲爱的微会员今天不是你的生日,你的生日日期是【"+member.getBirthday()+"】，暂不能享受生日优惠券,谢谢您的支持,请参与其它的优惠活动,谢谢!";
				writeToUser(reply);
				return ;
			}
		}
	}

	@Override
	public boolean isNeedBeMember() {
		return true;
	}

}
